<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户" prop="userId">
        <el-select size="small" v-model="queryParams.userId" placeholder="请选择用户名称" clearable filterable>
          <el-option v-for="(dict,index) in userList" :key="index" :label="dict.userName" :value="dict.userId"/>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="店铺id" prop="storeId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.storeId"-->
      <!--          placeholder="请输入店铺id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!--        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeUserRelateList" @selection-change="handleSelectionChange"
              :tree-props="{children: 'storeGradRelateList'}" row-key="id" border stripe>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户名" prop="userName" width="250">
        <template slot-scope="scope">
          <span class="text-info">
            {{ scope.row.userName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" prop="storeName" min-width="180">
        <template slot-scope="scope">
          <div v-if="scope.row.storeUserGradList">
            {{ scope.row.storeName }}
            <!--            <el-select disabled size="small" v-model="scope.row.storeId" placeholder="请选择店铺名称" clearable-->
            <!--                       filterable>-->
            <!--              <el-option v-for="(dict,index) in storeList" :key="index" :label="dict.storeName" :value="dict.id"/>-->
            <!--            </el-select>-->
          </div>
        </template>
      </el-table-column>
      <el-table-column label="店铺账号" align="center" prop="storeUserName" min-width="180">
        <template slot-scope="scope">
          <div v-if="scope.row.storeUserGradList">
            {{ scope.row.storeUserName }}
            <!--            <el-select disabled size="small" v-model="scope.row.storeId" placeholder="请选择店铺名称" clearable-->
            <!--                       filterable>-->
            <!--              <el-option v-for="(dict,index) in storeList" :key="index" :label="dict.storeName" :value="dict.id"/>-->
            <!--            </el-select>-->
          </div>
        </template>
      </el-table-column>
      <el-table-column label="提成分配" align="center" prop="evaluationTime" width="250">
        <template slot-scope="scope">
          <div v-if="scope.row.storeUserGradList">
            <div class="mb5 flex-between" v-for="(item,index) in scope.row.storeUserGradList" :key="index">
              <div class="mr10">
                {{ item.grad }}元以上利润
                <!--                <el-input disabled placeholder="请输入金额" size="small" style="width: 180px" v-model="item.grad">-->
                <!--                  <template slot="append">元以上利润</template>-->
                <!--                </el-input>-->
              </div>
              <div>
                {{ item.gradRate }}%提成
                <!--                <el-input disabled placeholder="请输入比例" style="width: 180px" size="small" v-model="item.gradRate">-->
                <!--                  <template slot="append">%提成</template>-->
                <!--                </el-input>-->
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <div v-if="!scope.row.storeUserGradList">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </div>
          <!--          <div v-else>-->
          <!--            <el-button @click="addAllocation(scope.row)" icon="el-icon-plus" circle></el-button>-->
          <!--            <el-button @click="cutAllocation(scope.row)" icon="el-icon-minus" circle></el-button>-->
          <!--          </div>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户店铺维护关联对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名称" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户名称" clearable filterable>
            <el-option v-for="(dict,index) in userList" :key="index" :label="dict.userName" :value="dict.userId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺名称">
          <div v-for="(storeItem,storeIndex) in form.storeGradRelateList">
            <div>
              <el-select v-model="storeItem.storeId" placeholder="请选择店铺名称" clearable filterable>
                <el-option v-for="(dict,index) in storeList" :key="index"
                           :label="dict.storeUserName + ' —— '+dict.storeName" :value="dict.id"/>
              </el-select>
            </div>
            <div class="mt10 flex" v-for="(item,index) in storeItem.storeUserGradList" :key="index">
              <div class="mr10">
                <el-input placeholder="请输入金额" size="small" style="width: 200px" v-model="item.grad">
                  <template slot="append">元以上利润</template>
                </el-input>
              </div>
              <div>
                <el-input placeholder="请输入比例" style="width: 200px" size="small" v-model="item.gradRate">
                  <template slot="append">%提成</template>
                </el-input>
              </div>
              <div class="ml20" v-if="index==0">
                <el-button size="small" @click="addAllocation(storeItem,storeIndex)" icon="el-icon-plus"
                           circle></el-button>
                <el-button size="small" @click="cutAllocation(storeItem,storeIndex)" icon="el-icon-minus"
                           circle></el-button>
              </div>
            </div>
            <el-divider></el-divider>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div class="flex-between">
          <div>
            <el-button size="small" :loading="buttonLoading" type="primary" @click="addStore">增加店铺</el-button>
            <el-button size="small" :loading="buttonLoading" type="danger" @click="cutStore">删除店铺</el-button>
          </div>
          <div>
            <el-button size="small" :loading="buttonLoading" type="primary" @click="submitForm">确定</el-button>
            <el-button size="small" @click="cancel">取消</el-button>
          </div>
        </div>


      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStoreUserRelate,
  getStoreUserRelate,
  delStoreUserRelate,
  addStoreUserRelate,
  updateStoreUserRelate, getStoreList, getErpUserList
} from "@/api/commission/commission";

export default {
  name: "StoreUserRelate",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户店铺维护关联表格数据
      storeUserRelateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,
        storeId: undefined,
      },
      // 表单参数
      form: {
        storeGradRelateList: [{ //编辑的店铺数量列表
          "storeId": '',
          "storeUserGradList": [{
            "grad": '',
            "gradRate": ''
          }]
        }]
      },
      // 表单校验
      rules: {
        userId: [
          {required: true, message: "用户不能为空", trigger: "change"}
        ],
        storeId: [
          {required: true, message: "店铺不能为空", trigger: "change"}
        ],
        commission: [
          {required: true, message: "不能为空", trigger: "blur"}
        ],
      },
      storeList: [],//店铺列表
      userList: [],//用户列表

    };
  },
  created() {
    this.getList();
    this.getStoreList()
    this.getUserList()
  },
  methods: {
    // 确定提成分配
    submitCommission(item) {
      console.log('item', item)
    },
    // 增加店铺
    addStore() {
      let length = this.form.storeGradRelateList.length
      // if (length < 5) {
      this.form.storeGradRelateList.push({
        "storeId": '',
        "storeUserGradList": [{
          "grad": '',
          "gradRate": ''
        }]
      })
      // } else {
      //   this.$message.info('数量已达上限！')
      // }
    },
    // 减少店铺
    cutStore() {
      let length = this.form.storeGradRelateList.length
      if (length > 1) {
        this.form.storeGradRelateList.splice(length - 1, 1)
      } else {
        this.$message.info('请至少保留1条！')
      }
    },
    // 增加提成分配
    addAllocation(storeItem) {
      console.log('增加分配', storeItem)
      if (!storeItem.storeId) {
        this.$message.error('请先选择店铺')
        return
      }
      let length = storeItem.storeUserGradList.length;
      let storeData = this.form.storeGradRelateList;
      for (let i = 0; i < storeData.length; i++) {
        if (storeData[i].storeId == storeItem.storeId) {
          // if (length < 5) {
          this.form.storeGradRelateList[i].storeUserGradList.push({
            "grad": '',
            "gradRate": ''
          })
          // } else {
          //   this.$message.info('数量已达上限！')
          // }

        }
      }
    },
    // 删除提成分配
    cutAllocation(storeItem, index) {
      let list = this.form.storeGradRelateList;
      let length = storeItem.storeUserGradList.length;
      if (length > 1) {
        for (let i = 0; i < list.length; i++) {
          if (index == i) {
            this.form.storeGradRelateList[i].storeUserGradList.splice(length - 1, 1)
          }
        }
      } else {
        this.$message.info('请至少保留1条！')
      }
    },
    // 获取用户列表
    getUserList() {
      getErpUserList().then(res => {
        this.userList = res.data.sysUserList
      })
    },
    // 获取店铺账号选择列表
    getStoreList() {
      this.loading = true;
      getStoreList().then(res => {
        this.storeList = res.data.empowerList;
        this.loading = false;
      });
    },
    /** 查询用户店铺维护关联列表 */
    getList() {
      this.loading = true;
      listStoreUserRelate(this.queryParams).then(response => {
        this.storeUserRelateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,
        storeId: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        storeGradRelateList: [{
          "storeId": '',
          "storeUserGradList": [{
            "grad": '',
            "gradRate": ''
          }]
        }],
        // storeUserGradList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户店铺提成配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getStoreUserRelate(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.oldUserId = response.data.userId
        this.open = true;
        this.title = "修改用户店铺提成配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // if (this.form.storeUserGradList.some((val) => val.gradRate == '')) {
          //   this.$message.error('提成金额不能为空！')
          //   return
          // }
          // if (this.form.storeUserGradList.some((val) => val.grad == '')) {
          //   this.$message.error('提成比例不能为空！')
          //   return
          // }
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateStoreUserRelate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addStoreUserRelate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.userId || this.ids;
      this.$modal.confirm('是否确认删除该用户数据？').then(() => {
        this.loading = true;
        return delStoreUserRelate(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('seller/storeUserRelate/export', {
        ...this.queryParams
      }, `storeUserRelate_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
